package logic

import (
	"context"
	"encoding/json"
	"time"
	"users/models/cache"
	"users/models/mysql"

	"users/usersrpc/internal/svc"
	"users/usersrpc/usersrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type ListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ListLogic {
	return &ListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ListLogic) List(in *usersrpc.ListRequest) (*usersrpc.ListResponse, error) {
	// todo: add your logic here and delete this line

	var users []mysql.User
	cacheData, _ := cache.Rdb.Get(cache.Ctx, "listUsers").Result()
	if cacheData == "" {
		mysql.DB.Find(&users)
		jsonData, _ := json.Marshal(users)
		cache.Rdb.Set(cache.Ctx, "listUsers", jsonData, time.Hour)
	} else {
		json.Unmarshal([]byte(cacheData), &users)
	}

	var listUsers []*usersrpc.ListUser
	for _, user := range users {
		list := usersrpc.ListUser{
			Username: user.Username,
			Email:    user.Email,
			Id:       int64(user.ID),
		}
		listUsers = append(listUsers, &list)
	}

	return &usersrpc.ListResponse{
		List: listUsers,
	}, nil
}
